package com.atguigu.service.impl;


import com.atguigu.annotations.MyRedisCache;
import com.atguigu.entities.TUser;
import com.atguigu.service.TUserService;
import com.atguigu.mapper.TUserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author shenhao
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2024-11-05 20:29:12
*/
@Slf4j
@Service
public class TUserServiceImpl implements TUserService{
    @Resource
    private TUserMapper tUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    public static final String CACHE_KEY_USER="user:";
    // =========第三组, 使用@MyRedisCache+ mysql
    @Override
    public int addUser(TUser user) {
        log.info("插入之前user:{}",user);
        int retValue = tUserMapper.insert(user);
        log.info("插入之后user:{}",user);
        // 插入成功, 放入redis中
        if (retValue>0){
            //到数据库里面，重新捞出新数据出来，做缓存
            user = tUserMapper.selectByPrimaryKey(user.getId());
            //缓存key
            String key = CACHE_KEY_USER+user.getId();
            redisTemplate.opsForValue().set(key,user);
        }
        return retValue;
    }
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    // 这个注解必须使用#号开头,但是可以修改
    @Override
    public TUser getUserById(int id) {
        return tUserMapper.selectByPrimaryKey(id);
    }
    // ===========第二组, redis+mysql
    /*public static final String CACHE_KEY_USER="user:";
    @Override
    public int addUser(TUser user) {
        log.info("插入之前user:{}",user);
        int retValue = tUserMapper.insert(user);
        log.info("插入之后user:{}",user);
        // 插入成功, 放入redis中
        if (retValue>0){
            //到数据库里面，重新捞出新数据出来，做缓存
            user = tUserMapper.selectByPrimaryKey(user.getId());
            //缓存key
            String key = CACHE_KEY_USER+user.getId();
            redisTemplate.opsForValue().set(key,user);
        }
        return retValue;
    }

    @Override
    public TUser getUserById(int id) {
        TUser user = null;
        //缓存key
        String key = CACHE_KEY_USER+id;
        //1 查询redis
        user = (TUser) redisTemplate.opsForValue().get(key);
        //redis无，进一步查询mysql
        if (user==null){
            user = tUserMapper.selectByPrimaryKey(id);
            // mysql有，redis无
            if (user!=null){
                //把mysql捞到的数据写入redis，方便下次查询能redis命中。
                redisTemplate.opsForValue().set(key,user);
            }
        }
        return user;
    }*/
    // 第一组, 只有MySQL
    /*@Override
    public int addUser(TUser user) {
        //return tUserMapper.insertUser(user);
        return tUserMapper.insert(user);
    }

    @Override
    public TUser getUserById(int id) {
        return tUserMapper.selectByPrimaryKey(id);
    }*/
}




